<?php namespace App\Http\Controllers;

use App\Admin;
use App\Banner;
use App\BooksChapter;
use App\BooksInfo;
use App\Classify;
use App\Http\Controllers\Api\AudioController;
use App\Http\Services\FileManager;
use App\UserVip;
use App\VipRule;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use App\RechargePackage;
use App\User;
use App\UserInfo;
use App\UserSpendRecord;
use Illuminate\Contracts\Auth\Guard;
use DB;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class AdminController extends Controller
{
    public function login(){
        return view('admin.login');
    }

    public function bannerList(){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var Banner $sysBanner */
        $sysBanners = Banner::orderBy('sort','asc')->orderBy('created_at','desc')->get();
        if(count($sysBanners) > 0){
            foreach($sysBanners as $sysBanner){
                $sysBanner->img_url = FileManager::getImgUrl($sysBanner->img_id);
            }
        }

        return view('admin.banner-list',['banners'=>$sysBanners]);
    }

    public function bannerSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var Banner $thatBanner */
        $thatBanner = Banner::whereId($id)->first();
        if($thatBanner){
            $thatBanner->img_url = FileManager::getImgUrl($thatBanner->img_id);
        }

        return view('admin.banner-set',['banner'=>$thatBanner]);
    }

    public function userList(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $keyword = $request->get("keyword");

        if(!is_null($keyword)){
            $userIds = UserInfo::where("nickname","like","%".$keyword."%")->pluck("user_id")->toArray();
            $users = User::whereIn("id",$userIds)->orderBy("created_at","desc")->paginate(50);
        }else{
            $users = User::orderBy("created_at","desc")->paginate(50);
        }


        foreach($users as $user){
            /** @var User $user */
            $user->userInfo;
            $user->userInfo->photo_url = FileManager::getImgUrl($user->userInfo->photo_id);

            $thatUserVip = UserVip::whereUserId($user->id)->first();
            $user->user_vip = $thatUserVip ? $thatUserVip : null;
        }

        $vipRules = VipRule::whereType("global_vip")->get();

        return view('admin.user-list',["users"=>$users,"vip_rules"=>$vipRules,"keyword"=>$keyword]);
    }

    public function userVipList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $nickname = $request->get('nickname');

        $thisUserVIpList = DB::table('user_vip')->whereNull('deleted_at');

        if(!is_null($nickname) && $nickname != ''){
            $thisUserIds = UserInfo::where('nickname','like','%'.$nickname.'%')->lists('user_id');
            $thisUserVIpList->whereIn('user_id',$thisUserIds);
        }

        /** @var UserVip $thisUserVIp */
        $thisUserVIpList = $thisUserVIpList->orderBy('created_at','desc')->paginate(30);
        if(count($thisUserVIpList) > 0){
            foreach($thisUserVIpList as $thisUserVIp){
                /** @var UserInfo $thisUserInfo */
                $thisUserInfo = UserInfo::whereUserId($thisUserVIp->user_id)->first();
                if($thisUserInfo){
                    $thisUserVIp->nickname = $thisUserInfo->nickname;
                    $thisUserVIp->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                }else{
                    $thisUserVIp->nickname = null;
                    $thisUserVIp->photo_url = null;

                }

                /** @var Classify $thisClassify */
                $thisClassify = Classify::whereId($thisUserVIp->classify_id)->first();
                if($thisClassify){
                    $thisUserVIp->classify_name = $thisClassify->name;
                }else{
                    $thisUserVIp->classify_name = null;
                }
            }
        }

        return view('admin.user-vip-list',['thisUserVIpList' => $thisUserVIpList,'nickname' => $nickname]);
    }

    public function adminList(Request $request)
    {
        if (Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var Admin $newAdmin */
        $newAdmins = Admin::orderBy('created_at', 'desc')->paginate(10);

        return view('admin.admin-list', ['admins' => $newAdmins]);
    }

    public function adminSet(Request $request)
    {
        if (Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        return view('admin.admin-set');
    }

    public function booksWordList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var BooksInfo $booksWord */
        $booksWords = BooksInfo::orderBy('created_at','desc')->paginate(30);

        if(count($booksWords)>0){
            foreach($booksWords as $booksWord){
               $classify=Classify::whereId($booksWord->classify_id)->first();
               if (!$classify){
                   $booksWord->classify_name="请给书籍分类";
               }else {
                   $booksWord->classify_name = $classify->name;
               }

               $booksWord->img_url = FileManager::getImgUrl($booksWord->img_id);
            }

        }



        return view('admin.books-word-list',['booksWords' => $booksWords,'classify'=>$classify]);
    }

    public function booksWordSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var BooksInfo $thisBooksWord */
        $thisBooksWord = BooksInfo::whereId($id)->first();
        if($thisBooksWord){
            $thisBooksWord->img_url = FileManager::getImgUrl($thisBooksWord->img_id);
        }
        $classifies=Classify::orderBy('created_at','desc')->get();

        return view('admin.books-word-set',['thisBooksWord' => $thisBooksWord,'classifies'=>$classifies]);
    }

    public function booksChapterList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $booksInfoId = !is_null($request->get('books_info_id')) ? $request->get('books_info_id') : 0;

        /** @var BooksChapter $booksChapter */
        $booksChapters = BooksChapter::whereBooksInfoId($booksInfoId)->orderBy('sort','asc')->paginate(30);
        if(count($booksChapters) > 0){
            foreach($booksChapters as $booksChapter){
                /** @var BooksInfo $thisBooksInfo */
                $thisBooksInfo = BooksInfo::whereId($booksChapter->books_info_id)->first();
                if($thisBooksInfo){
                    $booksChapter->books_Info = $thisBooksInfo;
                }else{
                    $booksChapter->books_Info = null;
                }

                $booksChapter->audio_url = route('Api.Audio.getAudioUrl',['audio_id' => $booksChapter->audio_id]);
            }
        }

        $booksInfo = BooksInfo::whereId($booksInfoId)->first();

        return view('admin.books-chapter-list',['booksChapters' => $booksChapters,'booksInfoId' => $booksInfoId,'booksInfo' => $booksInfo]);
    }

    public function booksChapterSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $booksInfoId = !is_null($request->get('books_info_id')) ? $request->get('books_info_id') : 0;
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var BooksChapter $thisBooksChapter */
        $thisBooksChapter = BooksChapter::whereId($id)->whereBooksInfoId($booksInfoId)->first();
        if($thisBooksChapter){
            $thisBooksChapter->audio_url = route('Api.Audio.getAudioUrl',['audio_id' => $thisBooksChapter->audio_id]);
        }

        $booksInfo = BooksInfo::whereId($booksInfoId)->first();

        return view('admin.books-chapter-set',['thisBooksChapter' => $thisBooksChapter,'booksInfoId' => $booksInfoId,'booksInfo' => $booksInfo]);
    }

    public function rechargePackageList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $rechargePackages = RechargePackage::orderBy('sort','asc')->orderBy('created_at','desc')->paginate(30);

        return view('admin.recharge-package-list',['rechargePackages' => $rechargePackages]);
    }

    public function rechargePackageSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisRechargePackage = RechargePackage::whereId($id)->first();

        return view('admin.recharge-package-set',['thisRechargePackage' => $thisRechargePackage]);
    }

    public function rechargeList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $nickname = $request->get('nickname');

        /** @var UserSpendRecord $userSpendRecord */
        $userSpendRecords = UserSpendRecord::whereType('books_coin');

        if(!is_null($nickname) && $nickname != ''){
            $thisUserIds = UserInfo::where('nickname','like','%'.$nickname.'%')->lists('user_id');
            $userSpendRecords->whereIn('user_id',$thisUserIds);
        }

        $userSpendRecords = $userSpendRecords->orderBy('created_at','desc')->paginate(30);
        if(count($userSpendRecords) > 0){
            foreach($userSpendRecords as $userSpendRecord){
                /** @var UserInfo $thisUser */
                $thisUser = UserInfo::whereUserId($userSpendRecord->user_id)->first();
                if($thisUser){
                    $userSpendRecord->nickname  = $thisUser->nickname;
                    $userSpendRecord->photo_url = FileManager::getImgUrl($thisUser->photo_id);
                }else{
                    $userSpendRecord->nickname  = null;
                    $userSpendRecord->photo_url = null;

                }

                /** @var RechargePackage $thisRechargePackage */
                $thisRechargePackage = RechargePackage::whereId($userSpendRecord->recharge_package_id)->first();
                if($thisRechargePackage){
                    $userSpendRecord->books_coin_num = (int)$thisRechargePackage->books_coin + (int)$thisRechargePackage->gift_books_coin;
                }else{
                    $userSpendRecord->books_coin_num = 0;
                }

                if($userSpendRecord->pay_type == 'wechat'){
                    $userSpendRecord->pay_type = '微信';
                }else{
                    $userSpendRecord->pay_type = '阅读币';
                }
            }
        }

        return view('admin.recharge-list',['userSpendRecords' => $userSpendRecords,'nickname' => $nickname]);
    }

    public function vipBuyList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $nickname = $request->get('nickname');

        /** @var UserSpendRecord $thisVIp */
        $thisVIpList = UserSpendRecord::whereType('vip');

        if(!is_null($nickname) && $nickname != ''){
            $thisUserIds = UserInfo::where('nickname','like','%'.$nickname.'%')->lists('user_id');
            $thisVIpList->whereIn('user_id',$thisUserIds);
        }

        $thisVIpList = $thisVIpList->orderBy('created_at','desc')->paginate(30);
        if(count($thisVIpList) > 0){
            foreach($thisVIpList as $thisVIp){
                /** @var UserInfo $thisUserInfo */
                $thisUserInfo = UserInfo::whereUserId($thisVIp->user_id)->first();
                if($thisUserInfo){
                    $thisVIp->nickname = $thisUserInfo->nickname;
                    $thisVIp->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);
                }else{
                    $thisVIp->nickname = null;
                    $thisVIp->photo_url = null;

                }

                /** @var VipRule $thatVipRule */
                $thatVipRule = VipRule::whereId($thisVIp->vip_rule_id)->first();
                if($thatVipRule){
                    /** @var Classify $thisClassify */
                    $thisClassify = Classify::whereId($thatVipRule->classify_id)->first();
                    if($thisClassify){
                        $thisVIp->classify_name = $thisClassify->name;
                    }else{
                        $thisVIp->classify_name = null;
                    }

                    $thisVIp->vip_rule_name = $thatVipRule->name;
                    $thisVIp->vip_rule_type = $thatVipRule->type;
                }else{
                    $thisVIp->classify_name = null;
                    $thisVIp->vip_rule_name = null;
                    $thisVIp->vip_rule_type = null;
                }

                if($thisVIp->pay_type == 'wechat'){
                    $thisVIp->pay_type = '微信';
                }else{
                    $thisVIp->pay_type = '阅读币';
                }
            }
        }

        return view('admin.vip-buy-list',['thisVIpList' => $thisVIpList,'nickname' => $nickname]);
    }

    public function buyBookList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $nickname = $request->get('nickname');

        /** @var UserSpendRecord $userSpendRecord */
        $userSpendRecords = UserSpendRecord::whereBetween('type',['book','book_chapter']);

        if(!is_null($nickname) && $nickname != ''){
            $thisUserIds = UserInfo::where('nickname','like','%'.$nickname.'%')->lists('user_id');
            $userSpendRecords->whereIn('user_id',$thisUserIds);
        }

        $userSpendRecords = $userSpendRecords->orderBy('created_at','desc')->paginate(30);
        if(count($userSpendRecords) > 0){
            foreach($userSpendRecords as $userSpendRecord){
                /** @var UserInfo $thisUser */
                $thisUser = UserInfo::whereUserId($userSpendRecord->user_id)->first();
                if($thisUser){
                    $userSpendRecord->nickname  = $thisUser->nickname;
                    $userSpendRecord->photo_url = FileManager::getImgUrl($thisUser->photo_id);
                }else{
                    $userSpendRecord->nickname = null;
                }

                if($userSpendRecord->type == 'book'){
                    $userSpendRecord->type = '整本书';

                    /** @var BooksInfo $thisBooksInfo */
                    $thisBooksInfo = BooksInfo::whereId($userSpendRecord->books_id)->first();
                    if($thisBooksInfo){
                        $userSpendRecord->books_name = $thisBooksInfo->name;

                        if($thisBooksInfo->type == 'word'){
                            $userSpendRecord->books_type = '文字';
                        }else{
                            $userSpendRecord->books_type = '音频';
                        }

                    }else{
                        $userSpendRecord->books_type = null;
                        $userSpendRecord->books_name = null;
                    }
                }elseif($userSpendRecord->type == 'book_chapter'){
                    $userSpendRecord->type = '一章节';

                    /** @var BooksChapter $thisBooksChapter */
                    $thisBooksChapter = BooksChapter::whereId($userSpendRecord->books_id)->first();
                    if($thisBooksChapter){
                        /** @var BooksInfo $thisBooksInfo */
                        $thisBooksInfo = BooksInfo::whereId($thisBooksChapter->books_info_id)->first();
                        if($thisBooksInfo){
                            $userSpendRecord->books_name = $thisBooksInfo->name . "： " . $thisBooksChapter->name;
                        }else{
                            $userSpendRecord->books_name = null;
                        }

                        if($thisBooksInfo->type == 'word'){
                            $userSpendRecord->books_type = '文字';
                        }else{
                            $userSpendRecord->books_type = '音频';
                        }
                    }else{
                        $userSpendRecord->books_type = null;
                        $userSpendRecord->books_name = null;
                    }
                }else{
                    $userSpendRecord->type = null;
                }

                if($userSpendRecord->pay_type == 'wechat'){
                    $userSpendRecord->pay_type = '微信';
                }else{
                    $userSpendRecord->pay_type = '阅读币';
                }
            }
        }

        return view('admin.buy-book-list',['userSpendRecords' => $userSpendRecords,'nickname' => $nickname]);
    }

    public function incomeCountList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        //每日开始时间和结束时间
        $currentYear  = date('Y',time());
        $currentMonth = date('m',time());
        $currentDay   = date('d',time());
        $todayStartTime = mktime(0,0,0,$currentMonth,$currentDay,$currentYear);
        $todayEndTime   = mktime(23,59,59,$currentMonth,$currentDay,$currentYear);

        //每月开始时间和结束时间
        $thisMonthStartTime = date('Y-m-01 00:00:00', strtotime(date("Y-m")));
        $thisMonthEndTime = date('Y-m-d 23:59:59', strtotime("$thisMonthStartTime +1 month -1 day"));

        //总收入
        $totalIncome = UserSpendRecord::whereBetween('type',['books_coin','vip'])->sum('amount_money');

        //今日收入
        $todayIncome = UserSpendRecord::whereBetween('type',['books_coin','vip'])->whereBetween('created_at',[date('Y-m-d H:i:s',$todayStartTime),date('Y-m-d H:i:s',$todayEndTime)])->sum('amount_money');

        //本月收入
        $thisMonthIncome = UserSpendRecord::whereBetween('type',['books_coin','vip'])->whereBetween('created_at',[$thisMonthStartTime,$thisMonthEndTime])->sum('amount_money');

        return view('admin.income-count-list',[
            'totalIncome' => $totalIncome ? $totalIncome : 0.00,
            'todayIncome' => $todayIncome ? $todayIncome : 0.00,
            'thisMonthIncome' => $thisMonthIncome ? $thisMonthIncome : 0.00
        ]);
    }

    public function vipRuleList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $vipRuleList = VipRule::whereType('global_vip')->orderBy('sort','asc')->orderBy('created_at','desc')->paginate(30);

        return view('admin.vip_rule-list',['vipRuleList' => $vipRuleList]);
    }

    public function packageRuleList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var VipRule $packageRule */
        $packageRuleList = VipRule::whereType('classify_vip')->orderBy('sort','asc')->orderBy('created_at','desc')->paginate(30);
        if(count($packageRuleList) > 0){
            foreach($packageRuleList as $packageRule){
                /** @var Classify $thisClassify */
                $thisClassify = Classify::whereId($packageRule->classify_id)->first();
                if($thisClassify){
                    $packageRule->classify_name = $thisClassify->name;
                }else{
                    $packageRule->classify_name = null;
                }
            }
        }

        $classifyList = Classify::orderBy('sort','asc')->orderBy('created_at','desc')->get();

        return view('admin.package_rule-list',['packageRuleList' => $packageRuleList,'classifyList' => $classifyList]);
    }

    public function changePwd(){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        return view('admin.change-psw');
    }

    public function classifyList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $classify = Classify::orderBy('sort','asc')->orderBy('created_at','desc')->get();

        return view('admin.classify-list',['classify' => $classify]);
    }
}